//
//  SeckillDetailViewController.m
//  CPICApp
//
//  Created by zhiwei li on 13-3-26.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "SeckillDetailViewController.h"
#import "Config.h"
#import "UIImageView+WebCache.h"
#import "RCAlertViewUtil.h"
#import "NSString+SBJson.h"
#import "NSObject+SBJson.h"

@interface SeckillDetailViewController ()

@end

@implementation SeckillDetailViewController
@synthesize titleLabel;
@synthesize CommodityID;
@synthesize img_Url;
@synthesize progress;
@synthesize detailcontent;
@synthesize BigImage;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.title = @"秒杀产品详情";
        self.view.backgroundColor = [UIColor whiteColor];
    }
    return self;
}
-(void)back
{
}
-(id)initView:(NSString *)commodityID;
{
    self.CommodityID=commodityID;
    
    self = [super init];
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    IRow=0;
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bgimage= [accountDefaults objectForKey:@"UserDefaultBgKindKey"];
    
    if ([bgimage isEqualToString:@"蓝色主题风格"]) 
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
        ADD_LEFT_BUTTONITEM(@"back.png");
        ADD_TITLE_NAMEITEM(@"秒杀产品详情");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    else if([bgimage isEqualToString:@"棕色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88_01@2x.png");
        ADD_LEFT_BUTTONITEM(@"back_01.png");
        ADD_TITLE_NAMEITEM(@"秒杀产品详情");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773_01@2x"]];
    }
    else if([bgimage isEqualToString:@"重大节日皮肤"])
    {
        NSData *dataImg_02=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_02];
        NSLog(@"-------找到%@",dataImg_02);
        NSData *dataImg_03=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_03];
        NSData *dataImg_04=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_04];
        
        NSURL *urlSkinImg_02=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_02]];
        NSURL *urlSkinImg_03=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_03]];
        NSURL *urlSkinImg_04=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_04]];
        NSLog(@"-------找到333%@",urlSkinImg_02);
        
        UIImageView * LogoImage = [[UIImageView alloc]init];
        [LogoImage setImageWithURL:urlSkinImg_03 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(LogoImage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_03];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        LogoImage.image = [UIImage imageWithData:dataImg_03];
        LogoImage.frame = CGRectMake(0, 0, LogoImage.image.size.width/2, LogoImage.image.size.height/2);
        [self.view addSubview:LogoImage];
        
        //--------------------------
        UIButton * CallOutBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn1.frame = CGRectMake(10, 10, 109/2, 57/2);
        UIImageView * Back = [[UIImageView alloc]init];
        [Back setImageWithURL:urlSkinImg_02 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(Back.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_02];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [Back setImage:[UIImage imageWithData:dataImg_02]];
        [CallOutBtn1 setImage:Back.image forState:UIControlStateNormal];
        [CallOutBtn1 addTarget:self action:@selector(ClickCallOutBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn1];
        //--------------------------
        
        ADD_TITLE_NAMEITEM(@"秒杀产品详情");
        
        
        UIImageView *bgimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,44, self.view.frame.size.width, self.view.frame.size.height-44)];
        [bgimage setImageWithURL:urlSkinImg_04 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(bgimage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_04];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [bgimage setImage:[UIImage imageWithData:dataImg_04]];
        [self.view addSubview:bgimage];
        [bgimage release];
    }
    
    //自定义标题
    titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0 , 244, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    //设置Label背景透明
    titleLabel.font = [UIFont boldSystemFontOfSize:14.0];
    //设置文本字体与大小
    titleLabel.textColor = [UIColor whiteColor];
    //设置文本颜色
    titleLabel.textAlignment = UITextAlignmentLeft;
    // titleLabel.text = [AppDelegate app].InfoTitle;
    //设置标题
    self.navigationItem.titleView = self.titleLabel;
    
    
    //添加UITableview
    TableDetail = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, 100) style:UITableViewStyleGrouped];
	TableDetail.delegate = self;
	TableDetail.dataSource = self;
    
    TableDetail.opaque = NO;
    TableDetail.backgroundView = nil;
    TableDetail.autoresizingMask = UIViewContentModeTop;
    TableDetail.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    TableDetail.scrollEnabled=NO;
    TableDetail.backgroundColor = [UIColor clearColor];
    [self.view addSubview:TableDetail];
    
    //添加大图显示
    BigImage= [[UIImageView alloc]initWithFrame:CGRectMake(60, 130, 200, 130)];
    [self.view addSubview:BigImage];
    [BigImage release];
    
    //添加详细的信息内容
    UILabel * lbdetailcontent = [[UILabel alloc]initWithFrame:CGRectMake(10, 274, 200, 25)];
    lbdetailcontent.text = @"秒杀产品详细信息如下:"; 
    lbdetailcontent.font = [UIFont systemFontOfSize:14.0];
    [self.view addSubview:lbdetailcontent];
    [lbdetailcontent release];
    
    detailcontent= [[UITextView alloc]initWithFrame:CGRectMake(0, 304, 320, self.view.frame.size.height-274)];
    [detailcontent setEditable:NO];
    detailcontent.font = [UIFont systemFontOfSize:14.0];
    [self.view addSubview:detailcontent];
    [detailcontent release];
}

-(void) ClickCallOutBtn
{
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    [CommodityID release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return IRow;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *Identifier=@"Identifier";
    UITableViewCell *cell=(UITableViewCell *)[TableDetail dequeueReusableCellWithIdentifier:Identifier];
    UILabel *labelTag= [[UILabel alloc] init];
    [labelTag setFrame:CGRectMake(20, 5, 80, 30)];
    [labelTag setFont:[UIFont systemFontOfSize:14.0]];
    [labelTag setBackgroundColor:[UIColor clearColor]];
    
    
    UILabel *labelName = [[UILabel alloc] init];
    [labelName setFrame:CGRectMake(100, 5, 200, 30)];
    [labelName setFont:[UIFont systemFontOfSize:14.0]];
    [labelName setBackgroundColor:[UIColor clearColor]];
    if (cell==nil)
    {
        cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier]autorelease];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
        
        cell.backgroundColor = [UIColor colorWithRed:239.0f/255.0f green:239.0f/255.0f blue:239.0f/255.0f alpha:1.0f];
        
        UIView *view = [[UIView alloc] initWithFrame:cell.frame];
        
        [view addSubview:labelTag];
        [view addSubview:labelName];
        
        
        [labelTag release];
        [labelName release];
        
        [cell addSubview:view];
        [view release];
    }
    if (indexPath.row==0) {
        labelTag.text=@"产品名称:";
        labelName.text=commodityName;
    }
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}

-(void)setSeckillDetailRequest//向太保移动平台发送秒杀产品详情接口请求报文
{
    //NSLog(@"userinfodefault%@",[[NSUserDefaults standardUserDefaults] objectForKey:DICT_USER_INFO]);
    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
    if (dictUserInfo!=nil) {
        if ([dictUserInfo valueForKey:@"UserAccount"]) {
            NSLog(@"%@",[dictUserInfo valueForKey:@"UserAccount"]);
        }
    }
    else
    {
//        [self justShowMessage:@"用户还没登录,请登录系统" title:@"注意"];
//        return;
    }
    NSString * useraccount;
    if ([dictUserInfo valueForKey:@"UserAccount"]) {
        useraccount = [dictUserInfo valueForKey:@"UserAccount"];
    }
    else
    {
        useraccount=@"cpic";
    }
    
//    NSString *strRequestCode=@"RequestCode=50402";
    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    [dicRequest setObject:self.CommodityID forKey:@"CommodityID"];
    [dicRequest setObject:useraccount forKey:@"UserAccount"];
    NSString *strRequestJson=[dicRequest JSONRepresentation];
//    strRequestJson=[NSString stringWithFormat:@"&RequestData=%@",strRequestJson];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestJson];
//    NSString *strUrlEncod = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    NSURL *myurl = [NSURL URLWithString:strUrlEncod];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"秒杀产品详情请求报文为:%@",strUrl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"50402" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseFail:)];
    [request setDidFinishSelector:@selector(ResonseSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress) 
    {
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    };
}

- (void)ResonseSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    commodityName=[dictResponse valueForKey:@"commodityName"];
    contextImgUrl=[dictResponse valueForKey:@"bImgUrl"];
    detailInfo=[dictResponse valueForKey:@"commodityDetailInfo"];
    commodityCode=[dictResponse valueForKey:@"commodityCode"];
    //title=[dictResponse valueForKey:@"title"];
    
    detailcontent.text=detailInfo;
    contextImgUrl=[[NSString alloc]initWithFormat:@"%@%@",Image_Url,contextImgUrl];
    NSString *imgURL=[contextImgUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [BigImage setImageWithURL:[NSURL URLWithString:imgURL] placeholderImage:[UIImage imageNamed:@"placeholder"]];
    IRow=1;
    [TableDetail reloadData];
    
    [self setClickRateRequest];
}

- (void)ResponseFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}

-(void)setClickRateRequest//点击率接口
{
    //NSLog(@"userinfodefault%@",[[NSUserDefaults standardUserDefaults] objectForKey:DICT_USER_INFO]);
    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
    if (dictUserInfo!=nil) {
        if ([dictUserInfo valueForKey:@"UserAccount"]) {
            NSLog(@"%@",[dictUserInfo valueForKey:@"UserAccount"]);
        }
    }
    else
    {
        //[self justShowMessage:@"用户还没登录,请登录系统" title:@"注意"];
        //return;
    }
    NSString * useraccount;
    if ([dictUserInfo valueForKey:@"UserAccount"]) {
        useraccount = [dictUserInfo valueForKey:@"UserAccount"];
    }
    else
    {
        useraccount=@"cpic";
    }
//    NSString *strRequestCode=@"RequestCode=61601";
    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    [dicRequest setObject:self.CommodityID forKey:@"commodityID"];
    [dicRequest setObject:useraccount forKey:@"userAccount"];
    NSString *strRequestJson=[dicRequest JSONRepresentation];
//    strRequestJson=[NSString stringWithFormat:@"&RequestData=%@",strRequestJson];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestJson];
//    NSString *strUrlEncod = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    NSURL *myurl = [NSURL URLWithString:strUrlEncod];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"产品点击率请求报文为:%@",strUrl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"61601" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseClickRateFail:)];
    [request setDidFinishSelector:@selector(ResonseClickRateSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress)
    {
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    };
}

- (void)ResonseClickRateSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
}

- (void)ResponseClickRateFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}

-(void)dealloc
{
    
    [super dealloc];
    
}

@end
